<?php

class Antz_Form_Components_Select extends Antz_Form_Component
{
    protected $options = array();
    protected $type = 'select';
    protected $value = array();
    protected $multiple = false;
    protected $size = 1;

    public function __construct($name, $label, $value='', $afterText=''){
        $this->id = 'sel'.rand();
        if(!is_array($value)) $value = array($value);
        $this->aftertext = $afterText;
        $this->name = $name;
        $this->label = $label;
        $this->value = $value;
        $this->isXhtml(false);
    }

    public function add($title, $value=''){
        $selected = (in_array($value, $this->value)) ? true : false;
        if($value==='')$value = $title;
        $this->options[] = Antz::newObject('Antz_Form_Components_Option', array($title, $value, $selected));
        return $this->options[(count($this->options)-1)];
    }
    
    public function setMultiple($bool){
      $this->multiple = (bool) $bool;
    }
    
    public function setSize($size){
      $this->size = (int) $size;
    }

    public function addOptGroup($title, $value=''){
    	if($value=='') $value = $this->value;
    	else if(!is_array($value)) $value = array($value);
        $this->options[] = Antz::newObject('Antz_Form_Components_OptGroup', array($title, $value));
        return $this->options[count($this->options)-1];
    }

    public function render(){
    	$Antz = Antz::registry('Antz');
    	global $gCms;
    	  $size = 'size="'.$this->size.'"';
        $disabled = ($this->disabled) ? 'disabled="disabled"' : '';
        $multiple = ($this->multiple) ? 'multiple="multiple"' : '';
        if(Antz::isFormError($this->name)) $this->addClass('error');
        if($this->required) $this->aftertext = '<span class="required"><img src="'.$gCms->config['root_url'].'/modules/Antz/images/required.gif" alt="'.$Antz->Lang('required').'" /></span>'.$this->aftertext;
        $returnString = "\n".'<select name="'.$this->name.'" id="'.$this->getId().'" '.$this->renderParameters().$this->renderClasses().$disabled.' '.$multiple.' '.$size.'>';
        foreach($this->options as $option){
            $returnString .= "\n  ".$option->render();
        };
        if($this->showLabel){
            $returnString = '<label for="'.$this->getId().'">'.$this->label.'</label>'.$returnString;
        }
        $returnString .= "\n".'</select><div class="aftertext">'.$this->aftertext.'</div>';
        if($this->wrap) $returnString = $this->wrap($returnString);
        return $returnString;
    }

    public function breakOptGroup(){
        $this->optGroupOpen = false;
    }

}
